package middleware

import (
	"gin_server/internal/model"
	"gin_server/pkg/jwt"
	"gin_server/pkg/response"
	"strings"

	"github.com/gin-gonic/gin"
)

// Auth JWT认证中间件
func Auth() gin.HandlerFunc {
	return func(c *gin.Context) {
		// 获取Authorization头
		authHeader := c.GetHeader("Authorization")
		if authHeader == "" {
			response.Unauthorized(c, "请先登录")
			c.Abort()
			return
		}

		// 检查Bearer前缀
		parts := strings.SplitN(authHeader, " ", 2)
		if !(len(parts) == 2 && strings.ToLower(parts[0]) == "bearer") {
			response.Unauthorized(c, "认证格式错误")
			c.Abort()
			return
		}

		// 解析access token
		claims, err := jwt.ParseAccessToken(parts[1])
		if err != nil {
			response.Unauthorized(c, "认证已过期或无效，需要重新登录或刷新token")
			c.Abort()
			return
		}

		// 将用户信息存储到上下文中
		c.Set("user_id", claims.ID)
		c.Set("account", claims.Account)
		c.Set("self_account", claims.SelfAccount)
		c.Set("user_role", claims.UserRole)

		c.Next()
	}
}

// RoleAuth 权限控制中间件
func RoleAuth(roles ...model.UserRoleType) gin.HandlerFunc {
	return func(c *gin.Context) {
		// 获取用户角色
		userRole, exists := c.Get("user_role")
		if !exists {
			response.Unauthorized(c, "请先登录")
			c.Abort()
			return
		}

		// 检查是否有匹配的角色
		hasPermission := false
		for _, role := range roles {
			if userRole == role {
				hasPermission = true
				break
			}
		}

		// 没有权限
		if !hasPermission {
			response.Forbidden(c, "没有操作权限")
			c.Abort()
			return
		}

		c.Next()
	}
}
